﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Web.Mvc;

namespace MvcPatch
{
    internal static class DummyControllerCache<TController> where TController : Controller
    {
        static DummyControllerCache()
        {
            var asmName = new AssemblyName("Dummy-Controller-Assembly-" + Guid.NewGuid().ToString());
            var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
            var moduleBuilder = asmBuilder.DefineDynamicModule("Dummy-Controller-Module-" + Guid.NewGuid().ToString());
            var typeBuilder = moduleBuilder.DefineType(typeof(TController).FullName + "$Dummy", TypeAttributes.Public, typeof(TController));

            var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[0]);
            var ilGenerator = ctorBuilder.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ret);

            Instance = (TController)Activator.CreateInstance(typeBuilder.CreateType());
        }

        public static TController Instance { get; private set; }
    }
}
